//showNotification({
//    message: "Invalid Username & Password, Please try again.",
//    type: "error",
//    autoClose: true,
//    duration: 3
//});
$(document).ready(function(){
var pathname = window.location.pathname;
/*-------------------------------------------------------------*/    
    // Company Registration
    $("#regUser").on("click",function(){
        $(".companyRegistration").ajaxForm(function(data){
            if(data=="User was successfully saved."){
                $(".noti").html(setNotification("correct","correct","Your company was successfully registered. Please confirm your email address."))
                setTimeout(function(){
                    window.location.reload("/home");
                },3000);
                
            }else{
                $(".noti").html(data)
            }
        });
    });
/*-------------------------------------------------------------*/     
    


/*-------------------------------------------------------------*/     
    // Register User/member of the company
    $(".regUser").on("click",function(){
        var action = $(this).attr("data-user-action");
        var regId = $(this).attr("data-reg-id"); // registration id of the field
        
        var regEmail = $("#regEmail"+regId).val();
        var regDisplayName = $("#regDisplayName"+regId).val();
        var regFname = $("#regFname"+regId).val();
        var regLname = $("#regLname"+regId).val();
        var regPosition  = $("#regPosition"+regId).val();
        
        $(this).hide();
        $("#loadRegUser" + regId).show();
        
		if(regDisplayName!=""){
			
            // Save to the database
            $.post("/ajax/regUser",{regEmail:regEmail,regDisplayName:regDisplayName,regFname:regFname,
                regLname:regLname,regPosition:regPosition,action:action}, function(data){
                    if(data=="User was successfully saved."){
                        showNotification({
                            message: data,
                            type: "success",
                            autoClose: true,
                            duration: 3
                        });
                        $('input[type="text"]'+".regUserField"+regId).val(null);
                        $("#regUser" + regId).show();
                        $("#loadRegUser" + regId).hide();
                    }else{
                        if(data=="Your email is already registered."){
							showNotification({
								message: data,
								type: "error",
								autoClose: true,
								duration: 3
							});
                            $("#regEmail"+regId).addClass("frequired-red");
                            $("#regEmail"+regId).tooltip('show');
							 $("#regUser" + regId).show();
                        $("#loadRegUser" + regId).hide();
                        }else{
                            if(data=="Please type your correct email format."){
							showNotification({
                            message: data,
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                                $("#regEmail"+regId).addClass("frequired-red");
                                $("#regEmail"+regId).tooltip('show');
								 $("#regUser" + regId).show();
                        $("#loadRegUser" + regId).hide();
                            }
                        }
                    }
            });
		}else{
			requiredFields('input[type="text"]'+".regUserField"+regId);
			 showNotification({
				message: "Please fill those blank fields",
				type: "error",
				autoClose: true,
				duration: 3
			});
			$("#regUser" + regId).show();
                        $("#loadRegUser" + regId).hide();
		}
       
		
    });
    
        $(".regUserField").on("keyup",function(){
            var action = $(this).attr("data-req-action");
            if(action=="edit"){
                var regId = $(this).attr("data-user-id");
                requiredFields('input[type="text"]'+".usereditInfo_"+userID);
            }else{
                var regId = $(this).attr("data-reg-id"); // registration id of the field
                requiredFields('input[type="text"]'+".regUserField"+regId);
            }
            
        });
/*-------------------------------------------------------------*/         
       
        


/*-------------------------------------------------------------*/         
    // Editing User List
    $("body").on("click",".editUserListInfo", function(){
   
        userID = $(this).attr("data-user-id");
        type = $(this).attr("data-type");
            $.ajax({
                type : "POST",
                url  : "/ajax/regUser",
                data : {action:"getUserInfo",userID:userID},
                dataType : "json",
                success : function(result){
                    var ctr = 0;
                    $.each(result, function(id,val){
                        var userInformation = "";
                        ctr++;
                        userInformation += '<h3 class="fl-margin-bottom"><i class="icon-edit"></i> Edit User</h3>';
                        userInformation += '<div class="hr"></div>';
                        userInformation += '<div class="label_below2"><center>';
                            userInformation += result[id].images;
                        userInformation += '</center></div>';
                        userInformation += '<div class="Fields fl-margin-bottom">';
                            userInformation += '<div class="label_below2"> Email: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<input type="text" name="updateUser" id="update_email" value="' + result[id].email + '" class="fl-edituser usereditInfo_' + result[id].userID + ' input-medium" style="margin-top:5px;">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="Fields fl-margin-bottom">';
                            userInformation += '<div class="label_below2"> Firstname: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<input type="text" name="updateUser" id="update_firstname" value="' + result[id].firstName + '"class="fl-edituser  usereditInfo_' + result[id].userID + ' input-medium" style="margin-top:5px;">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="Fields fl-margin-bottom">';
                            userInformation += '<div class="label_below2"> Lastname: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<input type="text" name="updateUser" id="update_lastname" value="' + result[id].lastName + '"class="fl-edituser usereditInfo_' + result[id].userID + ' input-medium" style="margin-top:5px;">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="Fields fl-margin-bottom">';
                            userInformation += '<div class="label_below2"> Display Name: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<input type="text" name="updateUser" id="update_displayName" value="' + result[id].displayName + '"class="fl-edituser usereditInfo_' + result[id].userID + ' input-medium" style="margin-top:5px;">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="Fields fl-margin-bottom">';
                            userInformation += '<div class="label_below2"> Position: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<input type="text" name="updateUser" id="update_position" value="' + result[id].position + '"class="fl-edituser usereditInfo_' + result[id].userID + ' input-medium" style="margin-top:5px;">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="Fields fl-margin-bottom fl-margin-right" style="float:left;">';
                            userInformation += '<div class="label_basic"> Active: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<select class="usereditInfo_' + result[id].userID + ' input-medium" name="updateUser" id="update_active" style="margin-top:5px;">';
                                    if (result[id].isActive=="1") {
                                        var active = 'selected=selected';
                                    }else{
                                        var not_active = 'selected=selected';
                                    }
                                    userInformation += '<option ' + active + ' value="1">Yes</option>';
                                    userInformation += '<option ' + not_active + ' value="0">No</option>';
                                userInformation += '</select>';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="fields">';
                            userInformation += '<div class="label_basic"> Privileges: </div>';
                            userInformation += '<div class="input_position">';
                                userInformation += '<select class="usereditInfo_' + result[id].userID + ' input-medium" name="updateUser" id="update_privileges" style="margin-top:5px;">';
                                    
                                    
                                    if(result[id].userLeveID=="3"){
                                            var userSelect = "selected=selected";
                                    }
                                    if(result[id].userLeveID=="2"){
                                            var adminSelect = "selected=selected";
                                    }
                                    userInformation += '<option ' + adminSelect + ' value="2">Admin</option>';
                                    userInformation += '<option ' + userSelect + ' value="3">User</option>';
                                    
                                userInformation += '</select>';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        userInformation += '<div class="fields">';
                            userInformation += '<div class="label_basic"></div>';
                            userInformation += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                                userInformation += '<input type="button" data-type="' + type + '" class="btn-blueBtn updateEditUser fl-margin-right" data-id="' + result[id].userID + '"  id="" value="Update"> ';
                                userInformation += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
                            userInformation += '</div>';
                        userInformation += '</div>';
                        if(result.length==ctr){
                             var newDialog = new jDialog(userInformation, "","", "", "", function(){});
                            newDialog.themeDialog("modal2");
                        }
                        
                      
                    });
                     
                    
                }
            });
            
            
        //$(".cancelEditUser").on("click",function(){
        //    userID = $(this).attr("data-user-id");
        //    // Hide Label
        //        $(".userviewInfo_"+userID).show();
        //        $("#editUserListInfo_"+userID).show();
        //        $("#deleteUser_"+userID).show();
        //    
        //    // Show Field
        //        $(".usereditInfo_"+userID).hide();
        //        $("#cancelEditUser_"+userID).hide();
        //        $("#updateEditUser_"+userID).hide();
        //        
        //    requiredFields('input[type="text"]'+".usereditInfo_"+userID);
        //});
    });
 /*-------------------------------------------------------------*/    
    


/*-------------------------------------------------------------*/    
    // Delete User
    $("body").on("click",".deleteUserListInfo", function(){
       
        userID = $(this).attr("data-user-id");
        type = $(this).attr("data-type");
        action = "deleteUser";
        con = "Are you sure do you want to deactivate this user?";
      var newConfirm = new jConfirm(con, 'Confirmation Dialog','', '', '', function(r){
            if(r==true){
                $.post("/ajax/regUser",{action:action,loggedAccount:"del",userID:userID},function(data){
                    if(data=="Deactivate User logged."){
                        jConfirm("Deactivating logged account may cause of automatic log off. Do you want to proceed?", 'Confirmation Dialog','', '', '', function(res){
                            if(res==true){
                                $.post("/ajax/reguser",{action:action,loggedAccount:"logout",userID:userID},function(e){
                                    if(e=="User will now deactivate."){
                                        window.location.replace("/user/logout");
                                    }
                                });
                                
                            }
                        });
                    }else{
                        // Refresh Data table of user
                                
                                if(pathname=="/settings"){
                                    $("#loadUser").dataTable().fnDestroy(); 
                                    load.loadTableUser();
                                }else if(pathname=="/user_view/user_settings"){
                                    $("#loadUser").dataTable().fnDestroy(); 
                                    GetUserDataTable.defaultData();
                                    $("#loadDeactivatedUser").dataTable().fnDestroy(); 
                                    GetDeactivateUserDataTable.defaultData();
                                    $("#loadDeactivatedUser").css("width","100%");
                                }

                    }
                    
                    //$("#userInfo_"+userID).animate({ backgroundColor: "whiteSmoke" }, "fast")
                    //                .animate({ opacity: "hide" }, "slow");
                });
                
            }
        });
        newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
    });
/*-------------------------------------------------------------*/     
    



/*-------------------------------------------------------------*/    
    // Update User
    $("body").on("click",".updateEditUser", function(){
        userID = $(this).attr("data-id");
        type = $(this).attr("data-type");
        var editEmail = $("#update_email").val();
        var editFname = $("#update_firstname").val();
        var editLname = $("#update_lastname").val();
        var editDisplayName = $("#update_displayName").val();
        var editPosition = $("#update_position").val();
        var editActive = $("#update_active").val();
        var editPrivileges = $("#update_privileges").val();
  
        var action = "updateUser";
        requiredFields('input[type="updateUser"]'+".usereditInfo_"+userID);
            
        
            // Update to the database
            $.post("/ajax/regUser",{editEmail:editEmail,editFname:editFname,editLname:editLname,
                   editDisplayName:editDisplayName,editPosition:editPosition,editActive:editActive,
                   editPrivileges:editPrivileges,action:action,userID:userID,type:type}, function(data){
                    if(data=="User was successfully updated."){
                        showNotification({
                            message: data,
                            type: "success",
                            autoClose: true,
                            duration: 3
                        });
                        // Remove Dialog Box
                        $("#popup_container").remove();
                        $("#popup_overlay").remove();
                        
                        if(pathname=="/settings"){
                            if (type=="deactivate") {
                                // Refresh Data table of user
                                $("#loadUser").dataTable().fnDestroy(); 
                                load.loadTableUser();
                            }else if (type=="activate"){
                                $("#loadDeactivatedUser").dataTable().fnDestroy(); 
                                load.loadTableDeactivatedUser();
                                $("#loadDeactivatedUser").css("width","100%");
                            }
                        }else if(pathname=="/user_view/user_settings"){
                            $("#loadUser").dataTable().fnDestroy(); 
                            GetUserDataTable.defaultData();
                            $("#loadDeactivatedUser").dataTable().fnDestroy(); 
                            GetDeactivateUserDataTable.defaultData();
                            $("#loadDeactivatedUser").css("width","100%");
                        }
                        
                        
                        
                           
                    }else{
                        if(data=="Your email is already registered."){
                            //alert(data)
                            $("#update_email").addClass("frequired-red");
                            $("#update_email").tooltip('show');
                        }else{
                            if(data=="Please type your correct email format."){
                                //alert(data)
                                $("#editEmail"+userID).addClass("frequired-red");
                                $("#editEmail"+userID).tooltip('show');
                            }
                        }
                    }
            });
    });
/*-------------------------------------------------------------*/     
    



/*-------------------------------------------------------------*/
















Forgot_password.setDialog();

});








// Validation for the required fields
function requiredFields(attribute){
    // @data-req-action
    // Validate Registration Fields
    var isValid = true;
    $(attribute).each(function() {
        if ($.trim($(this).val()) == '') {
            isValid = false;
            $(this).addClass("frequired-red");
            $(this).tooltip('show');
        }
        else{
            $(this).removeClass("frequired-red");
            $(this).tooltip('destroy');
        }
    });
    if (isValid == false)
        //e.preventDefault();
        return true;
}

function setNotification(container,icon,msg){
    var ret="";
    ret += '<div class="notification_wrapper">';
        ret += '<div class="'+container+'">';
            ret += '<img src="/images/warning/'+icon+'.png" width="22" height="19" class="img-notification-position">';
            ret += '<div class="notification-position">';    
               ret += msg;
            ret += '</div>';
        ret += '</div>';
    ret += '</div>';
    return ret;
}

Forgot_password = {
    "setDialog" : function(){
        var self = this;
        $(".forgot_password").click(function(){
            var ret = "";
            ret += '<div style="float:left;width:50%;">';
                ret += '<h3 class="pull-left fl-margin-bottom">';
                    ret += '<i class="icon-asterisk"></i> ' + "Forgot Password";
                ret += '</h3>';
            ret += '</div>';
            //ret += '<div style="float:right;width:50%;text-align:right;margin-top:-5px;">';
            //    ret += '<input type="button" class="btn-basicBtn getFormForWorkflow" id="" value="Ok" node-data-id="" style="">';
            //ret += '</div>';
            ret += '<div class="hr"></div>';
                    ret += '<div class="fields">';
                        ret += '<div class="label_below2" style="font-weight:bold"> Email Address:</div>';
                        ret += '<div class="input_position">';
                            ret += '<input type="email" class="tip form-text email-forgot">';
                        ret += '</div>';
                    ret += '</div>';
                    ret += '<div class="fields">';
                        ret += '<div class="label_basic"></div>';
                        ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                            ret += '<input type="button" class="btn-blueBtn forgot_submit fl-margin-right" value="Ok"> ';
                            ret += '<input type="button" class="btn-basicBtn" id="popup_cancel" value="Cancel">';
                        ret += '</div>';
                    ret += '</div>';
           var newDialog = new jDialog(ret, "", "",  "", "", function() {
            });
           newDialog.themeDialog("modal2");
            $(".email-forgot").focus();
            self.forgot_password();
        })
    },
    "forgot_password" : function () {
        $(".forgot_submit").click(function (argument) {
            var email = $(".email-forgot").val();
            ui.block();
            $("#popup_cancel").click();
            $.post("/ajax/regUser",{action:"forgot_password",email:email},function (e) {
                try{
                    var data = JSON.parse(e);
                    showNotification({
                       message: data.message,
                       type: data.status,
                       autoClose: true,
                       duration: 5
                    });
                }catch(error){
                    showNotification({
                       message: "Please try again. Somethings going wrong",
                       type: "error",
                       autoClose: true,
                       duration: 5
                    });
                }

                ui.unblock();
            })
        })
    }
}